package mundo.java.client.view;

import java.util.Map.Entry;

import mundo.java.client.events.ListMessagesEvent;
import mundo.java.client.events.Event.Handler;
import mundo.java.client.messages.GreetingMessages;
import mundo.java.shared.GreetingAction;
import mundo.java.shared.GreetingResponse;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class ListMessagesView {
	@Inject
	public ListMessagesView(HandlerManager eventBus, final GreetingMessages messages) {
		final DialogBox dialog = new DialogBox(true);
		
		eventBus.addHandler(ListMessagesEvent.TYPE, new Handler<ListMessagesEvent>() {
			@Override
			public void onEvent(ListMessagesEvent e) {
				int n = e.messages.size();
				dialog.setText(messages.messagesCount(n));

				Widget res; 
				if (n==0)
					res = new HTML(messages.noMessageSent());
				else {
					Grid grid = new Grid(e.messages.size()+1, 2);
					grid.setText(0, 0, messages.message());
					grid.setText(0, 1, messages.userAgent());
					grid.setBorderWidth(1);
					
					int i = 1;
					for (Entry<GreetingAction, GreetingResponse> entry : e.messages.entrySet()) {
						grid.setText(i, 0, entry.getKey().getTextToServer());
						grid.setText(i++, 1, entry.getValue().getUserAgent());
					}
					res = grid;
				}
				RootPanel messagesPanel = RootPanel.get("messagesList");
				messagesPanel.clear();
				messagesPanel.add(res);
			}
		});
	}
}